import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 布局组件
import MainLayout from '@/layouts/MainLayout.vue'

// 首页和登录页面
const Login = () => import('@/views/Login.vue')
const Dashboard = () => import('@/views/Dashboard.vue')
const NotFound = () => import('@/views/NotFound.vue')

Vue.use(VueRouter)

// 路由配置
const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false, title: '登录' }
  },
  {
    path: '/',
    component: MainLayout,
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: Dashboard,
        meta: { title: '控制台', icon: 'el-icon-s-home' }
      },
      {
        path: 'products',
        name: 'Products',
        component: () => import('@/views/product/ProductList.vue'),
        meta: { title: '商品管理', icon: 'el-icon-goods', roles: ['admin', 'manager'] }
      },
      {
        path: 'products/create',
        name: 'CreateProduct',
        component: () => import('@/views/product/ProductForm.vue'),
        meta: { title: '添加商品', activeMenu: '/products', hidden: true }
      },
      {
        path: 'products/edit/:id',
        name: 'EditProduct',
        component: () => import('@/views/product/ProductForm.vue'),
        meta: { title: '编辑商品', activeMenu: '/products', hidden: true }
      },
      {
        path: 'orders',
        name: 'Orders',
        component: () => import('@/views/order/OrderList.vue'),
        meta: { title: '订单管理', icon: 'el-icon-s-order' }
      },
      {
        path: 'orders/:id',
        name: 'OrderDetail',
        component: () => import('@/views/order/OrderDetail.vue'),
        meta: { title: '订单详情', activeMenu: '/orders', hidden: true }
      },
      {
        path: 'users',
        name: 'Users',
        component: () => import('@/views/user/UserList.vue'),
        meta: { title: '用户管理', icon: 'el-icon-user', roles: ['admin'] }
      },
      {
        path: 'logistics',
        name: 'Logistics',
        component: () => import('@/views/logistics/LogisticsList.vue'),
        meta: { title: '物流管理', icon: 'el-icon-truck' }
      },
      {
        path: 'inventory',
        name: 'Inventory',
        component: () => import('@/views/inventory/InventoryList.vue'),
        meta: { title: '库存管理', icon: 'el-icon-box' }
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/Profile.vue'),
        meta: { title: '个人中心', hidden: true }
      },
      {
        path: 'settings',
        name: 'Settings',
        component: () => import('@/views/Settings.vue'),
        meta: { title: '系统设置', icon: 'el-icon-setting', roles: ['admin'] }
      }
    ]
  },
  {
    path: '/404',
    name: 'NotFound',
    component: NotFound,
    meta: { requiresAuth: false, title: '页面不存在' }
  },
  {
    path: '*',
    redirect: '/404'
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
  scrollBehavior: () => ({ y: 0 })
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title 
    ? `${to.meta.title} - ${process.env.VUE_APP_TITLE}`
    : process.env.VUE_APP_TITLE

  // 获取认证状态
  const token = store.getters['auth/token']
  const isLoggedIn = !!token
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth)
  
  // 检查是否需要认证
  if (requiresAuth && !isLoggedIn) {
    next({ name: 'Login', query: { redirect: to.fullPath } })
    return
  }
  
  // 检查角色权限
  if (isLoggedIn && to.meta.roles) {
    const userRoles = store.getters['auth/userRoles']
    if (!to.meta.roles.some(role => userRoles.includes(role))) {
      next({ name: 'Dashboard' })
      return
    }
  }
  
  // 已登录用户访问登录页，重定向到首页
  if (isLoggedIn && to.path === '/login') {
    next({ name: 'Dashboard' })
    return
  }
  
  next()
})

export default router 